# coding=utf-8

from flask import Blueprint, request, jsonify, json, make_response, redirect, g
from common.models.User import User
from common.models.log.AppAccessLog import AppAccessLog
from common.libs.user.UserLibs import UserLibs
from common.libs.Helper import ops_render, get_current_date, create_pages
from common.libs.UrlManager import UrlManager
from sqlalchemy import or_
from application import app,db
from web.controllers.BaseControllerHelper import *
from .Helper import *

route_account = Blueprint( 'account_page', __name__ )

@route_account.route( "/index" )
def index():
    """
    列表页
    :return:
    """
    context={}
    req = request.values
    query, pages, offset, limit = create_pages(10, User.query, request)
    if 'mix_kw' in req:
        rule = or_(User.nickname.ilike("%{0}%".format(req['mix_kw'])), User.mobile.ilike("%{0}%".format(req['mix_kw'])))
        query = query.filter(rule)

    if 'status' in req and int(req['status']) > -1:
        query = query.filter(User.status == int(req['status']))

    list = query.order_by( User.uid.asc() ).all()[ offset:limit ]
    context["list"] = list
    context["pages"] = pages
    context['search_con'] = req
    context['status_mapping'] = app.config['STATUS_MAPPING']
    return ops_render("/account/index.html", context=context)

@route_account.route( "/info", methods=["GET"])
def info() :
    """
    详细信息
    :return:
    """
    context = {}
    redirect_url = UrlManager.buildUrl("/account/index")
    req = request.args
    uid = int(req.get("id", 0))
    if uid < 1 :
        return redirect( redirect_url )
    user_info = User.query.filter_by(uid = uid).first()
    if not user_info :
        return redirect( redirect_url )
    query, pages, offset, limit = create_pages(10, AppAccessLog.query.filter(AppAccessLog.uid==uid), request)
    access_list = query.order_by(AppAccessLog.id.desc()).all()[offset:limit]
    context["user_info"] = user_info
    context["access_list"] = access_list
    context["pages"] = pages
    return ops_render("/account/info.html", context=context)

@route_account.route( "/set", methods=["GET", "POST"])
def set() :
    """
    添加或修改
    :return:
    """
    context = {}
    req = request.values
    resp = gene_response(msg="操作成功~~")
    user_info = None
    if request.method == "GET" :
        uid = int(req.get("uid", 0))
        if uid :
            user_info = User.query.filter_by( uid = uid ).first()
        context['user_info'] = user_info
        return ops_render("/account/set.html", context=context)

    uid = get_values_by_request(req, "uid")
    nickname = get_values_by_request(req, "nickname")
    mobile = get_values_by_request(req, "mobile")
    email = get_values_by_request(req, "email")
    login_name = get_values_by_request(req, "login_name")
    login_pwd = get_values_by_request(req, "login_pwd")

    if nickname is None or len(nickname) < 1:
        resp = gene_response(code=-1, msg="请输入符合规范的姓名")
        return jsonify(resp)
    if mobile is None or len(mobile) < 1:
        resp = gene_response(code=-1, msg="请输入符合规范的手机号码")
        return jsonify(resp)
    if email is None or len(email) < 1:
        resp = gene_response(code=-1, msg="请输入符合规范的邮箱")
        return jsonify(resp)
    if login_name is None or len(login_name) < 1:
        resp = gene_response(code=-1, msg="请输入符合规范的登录用户名")
        return jsonify(resp)
    if login_pwd is None or len(login_pwd) < 6:
        resp = gene_response(code=-1, msg="请输入符合规范的登录密码")
        return jsonify(resp)

    check_login_name = User.query.filter( User.login_name == login_name, User.uid != uid ).first()
    if check_login_name :
        resp = gene_response(code=-1, msg="该登录名已经存在~~")
        return jsonify(resp)


    user_info = User.query.filter_by( uid = uid ).first()

    if user_info :
        model_user = user_info
    else :
        model_user = User()
        model_user.created_time = get_current_date()
        model_user.login_salt = UserLibs.geneSalt()
    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    model_user.login_pwd = UserLibs.genePassword(login_pwd, model_user.login_salt)
    model_user.updated_time = get_current_date()

    db.session.add( model_user )
    db.session.commit()
    return jsonify(resp)


@route_account.route("/ops",methods = [ "POST" ])
def ops():
    context = {}
    req = request.values
    resp = gene_response(msg="操作成功~~")
    uid = get_values_by_request(req, "uid")
    act = get_values_by_request(req, "act")
    if not id :
        resp = gene_response(code=-1, msg="请选择要操作的账号~~")
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp = gene_response(code=-1, msg="操作有误，请重试~~")
        return jsonify(resp)

    user_info = User.query.filter_by(uid=uid).first()
    if not user_info:
        resp = gene_response(code=-1, msg="指定账号不存在~~")
        return jsonify(resp)

    if act == "remove":
        user_info.status = 0
    elif act == "recover":
        user_info.status = 1

    if user_info and user_info.uid == 1:
        resp['code'] = -1
        resp['msg'] = "该用户是演示账号，不准操作账号~~"
        return jsonify(resp)

    user_info.update_time = get_current_date()
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)